﻿using System;
using System.IO;
using System.Windows.Forms;
using System.Xml.Serialization;
using SerialDemo;

namespace WindowsFormsApplication1
{
    internal static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            var demoForm = new DemoForm();
            String filePath = @"list.xml";
            demoForm.Closed += delegate
                                   {
                                       // Serialization
                                       var s = new XmlSerializer(typeof (ShoppingList));
                                       TextWriter w = new StreamWriter(filePath);
                                       s.Serialize(w, demoForm.ShoppingList);
                                       w.Close();
                                   };

            demoForm.Shown += delegate
                                 {
                                     // Deserialization
                                     ShoppingList newList = null;
                                     try
                                     {
                                         var s = new XmlSerializer(typeof(ShoppingList));
                                         TextReader r = new StreamReader(filePath);
                                         newList = (ShoppingList)s.Deserialize(r);
                                         r.Close();
                                     }
                                     catch (IOException ioe)
                                     {
                                         MessageBox.Show(ioe.Message);
                                     }
                                     catch (Exception e)
                                     {
                                         MessageBox.Show(e.Message);
                                         File.Delete(filePath);
                                     }
                                     finally
                                     {
                                         // Hvað gerir '??' ?
                                         demoForm.ShoppingList = newList ?? new ShoppingList();
                                     }
                                 };

            // Hérna notfærum við okkur delegate s.b.r C
            demoForm.ShoppingItemClicked += new ShoppingItemClicked(ItemClickedHandler);

            Application.Run(demoForm);
        }

        // Þetta fall er að bindast við delegate ShoppingItemClicked sem er í DemoForm
        static bool ItemClickedHandler(Item item)
        {
            MessageBox.Show(String.Format("Item clicked with name {0}",item.Name));
            return false;
        }

    }
}